package org.firecloud.h5fun.controller.service;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.log4j.Logger;
import org.firecloud.h5fun.model.javabean.UserBean;
import org.json.JSONObject;
/**
 * 上传Project的封面图片Ajax方法调用URL：ajax_upload_project_image<br>
 * 必须登陆：true<br>
 * 必须管理：true<br>
 * 参数：<br>
 * imagefile，必须，上传的文件<br>
 * 注：无<br>
 * @author fc
 */
@MultipartConfig
public class AjaxUploadProjectImage extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		JSONObject json = new JSONObject();
		File imageFile = null;
		try {
			UserBean loginUser = (UserBean) req.getSession().getAttribute("loginUser");
			if (loginUser != null && loginUser.isAdmin()) {
			resp.setCharacterEncoding("UTF-8");
			resp.setContentType("application/json");
			String pathname = req.getServletContext().getRealPath("/files/image/");
			String filename = System.currentTimeMillis() + ".png";
			Part part = req.getPart("imagefile");
			BufferedImage bufferImage = ImageIO.read(part.getInputStream());
			imageFile = new File(pathname,filename);
			ImageIO.write(bufferImage, "PNG", imageFile);
			json.put("type", 0);
			json.put("filename", filename);
			}else{
				json.put("type", -2);
				json.put("msg", "权限不足");
			}
		} catch (Exception e) {
			json.put("type", -1);
			json.put("msg", e.getMessage());
			if(imageFile!=null && imageFile.exists()){
				imageFile.delete();
			}
			Logger.getRootLogger().error(e);
		}
		resp.getWriter().print(json);
	}
}
